﻿#include "sqlCommon.h"

SqlCommon::SqlCommon(QObject *parent) : QObject(parent) {
    db = QSqlDatabase::addDatabase("QSQLITE");
}

SqlCommon::~SqlCommon() {
    if (db.isOpen()) {
        db.close();
    }
}

// 打开 SQLite 数据库
bool SqlCommon::openDatabase(const QString &dbPath) {
    db.setDatabaseName(dbPath);
    if (!db.open()) {
        qDebug() << "数据库打开失败:" << db.lastError().text();
        return false;
    }
    return true;
}
//执行sql语句（queryStr：SQL 语句（可以包含 ? 占位符）。  args：绑定到 ? 的参数值列表。）
bool SqlCommon::executeQuery(const QString &queryStr, const QVariantList &args)
{
    QSqlQuery query(db);//创建sql查询对象
    query.prepare(queryStr);//预处理 SQL 语句


    for (int i = 0; i < args.size(); ++i)
    {
        query.bindValue(i, args[i]);// 将args 中的值逐个绑定到 SQL 语句中的 ? 位置。
    }

    if (!query.exec())//执行sql语句
    {
        QString errorMessage = "SQL 执行失败：\n" + query.lastError().text();
        QMessageBox::critical(nullptr, "数据库错误", errorMessage);
        return false;
    }
    return true;
}

QSqlQuery SqlCommon::selectQuery(const QString &queryStr) {
    QSqlQuery query(db);
    if (!query.exec(queryStr))
    {
        qDebug() << "查询失败：" << query.lastError().text();
    }
    return query;
}

// 获取材质全部信息
QSqlQueryModel* SqlCommon::getTableModel_material(QObject *parent) {
    if (!db.isOpen()) {
        qDebug() << "数据库未打开，无法执行查询！";
        return nullptr;
    }
    QSqlQueryModel *model = new QSqlQueryModel(parent);
    model->setQuery("SELECT * FROM MaterialProperty_T72 ORDER BY CAST(材质ID AS INTEGER) ASC", db);
    if (model->lastError().isValid()) {
        qDebug() << "查询执行失败:" << model->lastError().text();
        QString errorMessage=model->lastError().text();
        QMessageBox::critical(nullptr, "数据库查询失败", errorMessage);
        delete model;
        return nullptr;
    }
    return model;
}
//新增材质信息
bool SqlCommon::insertData_material(int materialNum, const QString &materialName, double temperature, double emissivity)
{
    QString sql = "INSERT INTO material (materialNum, materialName, temperature, emissivity) VALUES (?, ?, ?, ?)";
    QVariantList args = {materialNum, materialName, temperature, emissivity};
    return executeQuery(sql, args);
}
//更新材质信息
bool SqlCommon::updateData_material(int materialNum, const QString &newMaterialName, double newTemperature, double newEmissivity)
{
    QString sql = "UPDATE material SET materialName = ?, temperature = ?, emissivity = ? WHERE materialNum = ?";
    QVariantList args = {newMaterialName, newTemperature, newEmissivity, materialNum};
    return executeQuery(sql, args);
}
// 删除数据
bool SqlCommon::deleteData_material(int materialNum) {
    QString sql = "DELETE FROM material WHERE materialNum = ?";
    QVariantList args = {materialNum};
    return executeQuery(sql, args);
}
// 获取气溶胶全部信息
QSqlQueryModel* SqlCommon::getTableModel_modin(QObject *parent) {
    if (!db.isOpen()) {
        qDebug() << "数据库未打开，无法执行查询！";
        return nullptr;
    }
    QSqlQueryModel *model = new QSqlQueryModel(parent);
    model->setQuery("SELECT * FROM modin ORDER BY CAST(id AS INTEGER) ASC", db);
    // 设置列标题
    model->setHeaderData(0, Qt::Horizontal, "编号");
    model->setHeaderData(1, Qt::Horizontal, "大气廓线");
    model->setHeaderData(2, Qt::Horizontal, "气溶胶模式");
    model->setHeaderData(3, Qt::Horizontal, "季节");
    model->setHeaderData(4, Qt::Horizontal, "降雨强度");
    model->setHeaderData(5, Qt::Horizontal, "风速");
    model->setHeaderData(6, Qt::Horizontal, "海拔等级");
    if (model->lastError().isValid()) {
        qDebug() << "查询执行失败:" << model->lastError().text();
        QString errorMessage=model->lastError().text();
        QMessageBox::critical(nullptr, "数据库查询失败", errorMessage);
        delete model;
        return nullptr;
    }
    return model;
}
